package com.seal.commons.infrastructure.redis.configuration;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.seal.commons.infrastructure.facade.cache.RedisCommand;
import com.seal.commons.infrastructure.redis.command.DefaultRedisCommand;
import com.seal.commons.infrastructure.redis.configuration.lettuce.LettuceAutoConfiguration;
import com.seal.commons.infrastructure.redis.serialize.GenericJackson2JsonRedisSerializer;
import com.seal.commons.infrastructure.redis.serialize.StringRedisSerializer;
import io.lettuce.core.api.StatefulConnection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-07-16 22:28<br/>
 * @since JDK 1.8
 */
@Configuration
@AutoConfigureAfter(LettuceAutoConfiguration.class)
@Slf4j
public class RedisCommandAutoConfiguration {


    @Bean("redisCommand")
    @ConditionalOnBean(StatefulConnection.class)
    public RedisCommand RedisCommand(StatefulConnection<byte[], byte[]> statefulConnection){
        DefaultRedisCommand defaultRedisCommand = new DefaultRedisCommand(statefulConnection);

        ObjectMapper om = new ObjectMapper();
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(new JavaTimeModule());
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        defaultRedisCommand.setKeySerializer(new StringRedisSerializer());
        defaultRedisCommand.setHashKeySerializer(new StringRedisSerializer());
        defaultRedisCommand.setValueSerializer(new GenericJackson2JsonRedisSerializer(om));
        return defaultRedisCommand;
    }
}